<?php

namespace app_supplier\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\db\Query;

class User extends ActiveRecord implements IdentityInterface
{
    
    /**返回用户名
     * @return string
     */
    public static function tableName()
    {
        return '{{%auth_account}}';
    }
    /**
     * 根据id查询
     * @param int|string $id
     * @return static
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
        //return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @param mixed $token
     * @param null $type
     * @return static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['accessToken'=>$token]);
    }

    /**根据用户名查询用户
     * @param $username
     * @return static
     */
    public static function findByUsername($username)
    {
        return static::findOne(['account'=>$username]);

    }

    /**
     * 返回用户id
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->account;
    }

    /**获取authKey
     * @return mixed
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**认证key
     * @param string $authKey
     * @return bool
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**认证密码
     * @param $password
     * @return bool
     */
    public function validatePassword($password)
    {
        return $this->password === static::md5Pwd($password);
    }

    /**加密
     * @param $password
     * @return string
     */
    public static function md5Pwd($password)
    {
        return md5($password);
    }

    /**获取用户其他信息
     * @param $account
     * @param $pwd
     * @return array|bool
     */
    public static function findUserInfo($account, $pwd)
    {
        $list = (new Query())
            ->select(['a.account', 'a.password','d.*'])
            ->from('auth_account a')
            ->join('inner join ', 'auth_account_role  r', 'r.account_id=a.id')
            ->join('inner join ', 'dealer d', 'd.dealer_id=r.obj_id')
            ->where('a.account=:account and a.password=:pwd', [':account'=>$account, ':pwd'=>$pwd])
            ->andWhere('r.role_id=:role_id and r.groups_id=:groups_id', [':role_id'=>20, ':groups_id'=>11])
            ->one();
        return $list;
    }
}
